package cn.hj.config;

import cn.hj.beans.Person;
import cn.hj.mapper.PersonMapper;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.transaction.managed.ManagedTransactionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.mapper.MapperFactoryBean;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

/**
 * @author HP
 */
@Configuration
@ComponentScan
@MapperScan("cn.hj.mapper")
public class AppConfig {

    @Bean("zhangsan")
    public Person person(){
        return new Person("zhangsan", 18);
    }


    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {

       PooledDataSource source=new PooledDataSource();
       source.setDriver("com.mysql.cj.jdbc.Driver");
       source.setUrl("jdbc:mysql://192.168.0.123:3306/my_db?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8");
       source.setUsername("hj");
       source.setPassword("1234");
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(source);
        factoryBean.setTransactionFactory(new ManagedTransactionFactory());


        return factoryBean.getObject();
    }
    @Bean
    public MapperFactoryBean<PersonMapper> personMapper() throws Exception {

        MapperFactoryBean<PersonMapper> factoryBean = new MapperFactoryBean<>(PersonMapper.class);
        factoryBean.setSqlSessionFactory(sqlSessionFactory());

        return factoryBean;
    }

/*    @Bean
    public PersonMapper mapper() throws Exception {

        PooledDataSource source=new PooledDataSource();
        source.setDriver("com.mysql.cj.jdbc.Driver");
        source.setUrl("jdbc:mysql://192.168.0.123:3306/my_db?useUnicode=true&amp;characterEncoding=utf-8&amp;allowMultiQueries=true");
        source.setUsername("hj");
        source.setPassword("1234");
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(source);
        factoryBean.setTransactionFactory(new ManagedTransactionFactory());

        SqlSessionFactory sqlSessionFactory=factoryBean.getObject();

        MapperFactoryBean<PersonMapper> factoryBean2= new MapperFactoryBean<>(PersonMapper.class);
        factoryBean2.setSqlSessionFactory(sqlSessionFactory);


        SqlSessionTemplate sqlSessionTemplate = new SqlSessionTemplate(factoryBean2.getSqlSessionFactory());

        return sqlSessionTemplate.getMapper(PersonMapper.class);
    }*/


}
